package com.rpp.controller;

import com.rpp.config.DruidConfig;
import com.rpp.config.ZookeeperConfig;
import com.rpp.domain.Account;
import com.rpp.utils.DatasourceUtil;
import com.rpp.utils.JsonUtil;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author peng
 * @Date 2020/8/11 9:46 上午
 */
@RestController
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    ZkClient zkClient;

    /**
     * 查询数据源配置
     *
     * @return
     */
    @RequestMapping(value = "/config/get")
    public DruidConfig getConfig() {
        //读取数据源配置
        Object obj = zkClient.readData(ZookeeperConfig.DATASOURCE_NODE);
        if (null == obj) {
            return null;
        }
        DruidConfig config = JsonUtil.toObject(obj.toString(), DruidConfig.class);
        return config;
    }

    /**
     * 更新数据源配置
     *
     * @return
     */
    @RequestMapping(value = "/config/update")
    public String updateConfig() {
        DruidConfig druidConfig = new DruidConfig();
        druidConfig.setUrl("jdbc:mysql://47.94.80.41:3306/mybatis_test?serverTimezone=UTC");
        druidConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidConfig.setUserName("root");
        druidConfig.setPassword("rppizpy");
        druidConfig.setInitialSize(20);
        druidConfig.setMaxActive(50);
        druidConfig.setMinIdle(20);
        druidConfig.setMaxWait(5000);
        zkClient.writeData(ZookeeperConfig.DATASOURCE_NODE, JsonUtil.toJson(druidConfig));

        return "success";
    }

    /**
     * 查询数据
     *
     * @return
     */
    @RequestMapping(value = "/query")
    public List<Account> query() throws Exception {

        //获取连接
        Connection connection = DatasourceUtil.dataSource.getConnection();

        //查询数据
        String sql = "select * from tbl_account";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        List<Account> list = new ArrayList<>();
        while (resultSet.next()) {
            String name = resultSet.getString("name");
            int money = resultSet.getInt("money");
            String cardNo = resultSet.getString("cardNo");
            System.out.println(String.format("name:%s,money:%s,cardNo:%s", name, money, cardNo));

            list.add(new Account(name, money, cardNo));
        }
        return list;
    }
}
